//
//  XTLoopScrollView.m
//  XTLoopScroll
//
//  Created by TuTu on 15/10/30.
//  Copyright © 2015年 teason. All rights reserved.
//

#import "XTLoopScrollView.h"
#import "NSTimer+Addition.h"

static int IMAGEVIEW_COUNT = 3 ;

@interface XTLoopScrollView () <UIScrollViewDelegate>
{
    UIScrollView            *_scrollView ;
    
    UIImageView             *_leftImageView;
    UIImageView             *_centerImageView;
    UIImageView             *_rightImageView;
    UIPageControl           *_pageControl;
    
    UILabel                 *_label;
    
    int                     _imageCount;
    BOOL                    _bLoop ;
    NSInteger               _durationOfScroll ;

    NSTimer                 *_timerLoop ;           // 控制循环
    NSTimer                 *_timerOverflow ;       // 控制手动后的等待时间
    BOOL                    bOpenTimer ;            // 开关
    
    //title 13
    UILabel *labTitle;
    //price 14
    UILabel *labPrice;
    
}
@property (nonatomic)       int     currentImageIndex ;
@property (nonatomic,copy)  NSArray *imglist ; //dataSource list , string .

@end

@implementation XTLoopScrollView
@synthesize color_currentPageControl = _color_currentPageControl ,
            color_pageControl = _color_pageControl ,
            pageControl = _pageControl;

#pragma - Property
- (void)setColor_pageControl:(UIColor *)color_pageControl
{
    _color_pageControl = color_pageControl ;
    
    _pageControl.pageIndicatorTintColor = _color_pageControl ;
}

- (UIColor *)color_pageControl
{
    if (!_color_pageControl) {
        _color_pageControl = [UIColor grayColor] ;
    }
    return _color_pageControl ;
}

- (void)setColor_currentPageControl:(UIColor *)color_currentPageControl
{
    _color_currentPageControl = color_currentPageControl ;
    
    _pageControl.currentPageIndicatorTintColor = _color_currentPageControl ;
}

- (UIColor *)color_currentPageControl
{
    if (!_color_currentPageControl) {
        _color_currentPageControl = [UIColor darkGrayColor] ;
    }
    return _color_currentPageControl ;
}

#pragma - Initial
- (instancetype)initWithFrame:(CGRect)frame
                 andImageList:(NSArray *)imglist
                      canLoop:(BOOL)canLoop
                     duration:(NSInteger)duration
{
    self = [super init];
    if (self) {
        
//        self.frame = frame ;
//        _imglist = imglist ;
//        _imageCount = (int)self.imglist.count ;
//        _bLoop = canLoop ;
//        _durationOfScroll = duration ;
//        //显示分享注册 弹窗
//        [[NSNotificationCenter defaultCenter] addObserver:self
//                                                 selector:@selector(loopAction)//接收消息方法
//                                                     name:@"showNextPage"//消息识别名称
//                                                   object:nil];
//        self.backgroundColor = [UIColor whiteColor] ;
//        [self setup] ;
//        
//        if (_bLoop) {
//            [self loopStart] ;
//        }
      
    }
    
    return self;
}


- (void)startWithFrame:(CGRect)frame
          andImageList:(NSArray *)imglist
               canLoop:(BOOL)canLoop
              duration:(NSInteger)duration
          isOKYuandian:(BOOL)isss
{
    _isOkYuanDian = isss;
    self.frame = frame ;
    _imglist = imglist ;
    _imageCount = (int)self.imglist.count;
    _bLoop = canLoop ;
    _durationOfScroll = duration;
    
    if (!isss) {
        //显示蓝条跟着动
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(loopAction)//接收消息方法
                                                     name:@"showNextPage"//消息识别名称
                                                   object:nil];
    }
    
    self.backgroundColor = [UIColor whiteColor];
    [self setup];
    
    if (_bLoop) {
        [self loopStart];
    }
}

- (void)setup
{
    //添加滚动控件
    [self addScrollView];
    //添加图片控件
    [self addImageViews];
    //添加分页控件
    [self addPageControl];
    if (!_isOkYuanDian) {
        //添加底部黑色背景
        [self addSubBottomView];
    }
    
    //添加图片信息描述控件
    [self addLabel];
    //加载默认图片
    [self setDefaultImage];
}

- (void)loopStart
{
    if (_timerLoop == nil) {
        _timerLoop = [NSTimer timerWithTimeInterval:_durationOfScroll
                                             target:self
                                           selector:@selector(loopAction)
                                           userInfo:nil
                                            repeats:YES] ;
        
        [[NSRunLoop currentRunLoop] addTimer:_timerLoop
                                     forMode:NSDefaultRunLoopMode] ;
    }
    
}

- (void)loopAction
{
    int leftImageIndex , rightImageIndex ;
    _currentImageIndex = (_currentImageIndex + 1) % _imageCount ;
    
    [_centerImageView sd_setImageWithURL:_imglist[_currentImageIndex] placeholderImage:[UIImage imageNamed:@"img_normal1"]];
    
    
    leftImageIndex  = (_currentImageIndex + _imageCount - 1) % _imageCount ;
    rightImageIndex = (_currentImageIndex + 1) % _imageCount ;

    
    [_leftImageView sd_setImageWithURL:_imglist[leftImageIndex] placeholderImage:[UIImage imageNamed:@"img_normal1"]];
    
    [_rightImageView sd_setImageWithURL:_imglist[rightImageIndex] placeholderImage:[UIImage imageNamed:@"img_normal1"]];
    
    [_scrollView setContentOffset:CGPointMake(_scrollView.frame.size.width , 0) animated:NO];
    
    CATransition *animation = [CATransition animation];
    [animation setDuration:0.35f];
    [animation setType:kCATransitionPush];
    [animation setSubtype:kCATransitionFromRight];
    [animation setFillMode:kCAFillModeForwards];
    [animation setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut]];
    [_centerImageView.layer addAnimation:animation forKey:nil];
    
    _pageControl.currentPage=_currentImageIndex;
    _customPage.currentPage = _currentImageIndex;
    [_customPage setNeedsDisplay];
    
    if (_aryInfoData.count != 0) {
        labTitle.text = _aryInfoData[_currentImageIndex][@"title"];
        labPrice.text = [self comperNumber:_aryInfoData[_currentImageIndex][@"investment"]];
        
//        NSLog(@"价格------:%@",[self comperNumber:_aryInfoData[_currentImageIndex][@"investment"]]);
    }
    
    
}

#pragma mark - 添加底部黑色
- (void)addSubBottomView
{
    UIView *viewBack = [[UIView alloc] initWithFrame:(CGRect){0,142,screenW,30}];
    [viewBack setBackgroundColor:[[UIColor blackColor] colorWithAlphaComponent:0.6f]];
    
    //title
    labTitle = [[UILabel alloc] initWithFrame:(CGRect){8,5,210,20}];
    labTitle.font = [UIFont systemFontOfSize:13.0f];
    labTitle.textColor = [UIColor whiteColor];
    
    //资金
    UILabel *labZijin = [[UILabel alloc] initWithFrame:(CGRect){220,5,40,20}];
    labZijin.text = @"资金:";
    labZijin.font = [UIFont systemFontOfSize:13.0f];
    labZijin.textColor = [UIColor whiteColor];
    
    //price
    labPrice = [[UILabel alloc] initWithFrame:(CGRect){260,5,105,20}];
    labPrice.font = [UIFont systemFontOfSize:13.0f];
    labPrice.textColor = [UIColor colorWithRed:255.0f/255.0f green:107.0f/255.0f blue:80.0f/255.0f alpha:1.0f];
    
    [viewBack addSubview:labTitle];
    [viewBack addSubview:labZijin];
    [viewBack addSubview:labPrice];
    
    //[self addSubview:viewBack];
}

#pragma mark 添加控件
- (void)addScrollView
{
    if (!_scrollView) {
        _scrollView = [[UIScrollView alloc] init] ;
    }
    CGRect rect = CGRectZero ;
    rect.size = self.frame.size ;
    _scrollView.frame = rect ;
    
    _scrollView.delegate = self;
    //设置contentSize
    _scrollView.contentSize = CGSizeMake(IMAGEVIEW_COUNT * _scrollView.frame.size.width, _scrollView.frame.size.height) ;
    //设置当前显示的位置为中间图片
    [_scrollView setContentOffset:CGPointMake(_scrollView.frame.size.width, 0) animated:NO];
    
    _scrollView.pagingEnabled = YES;
    _scrollView.showsHorizontalScrollIndicator=NO;
    _scrollView.backgroundColor = [UIColor whiteColor];
    
    [self addSubview:_scrollView] ;
    
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapScrollView)] ;
    [_scrollView addGestureRecognizer:tapGesture] ;
}

- (void)tapScrollView
{
//    NSLog(@"tap : %d",self.currentImageIndex) ;
    [self.delegate tapingCurrentIndex:self.currentImageIndex andWho:self];
}

#pragma mark 添加图片三个控件
- (void)addImageViews
{
    _leftImageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];
    _leftImageView.contentMode = UIViewContentModeScaleToFill;
    [_scrollView addSubview:_leftImageView];
    _centerImageView = [[UIImageView alloc]initWithFrame:CGRectMake(self.frame.size.width, 0, self.frame.size.width, self.frame.size.height)];
    _centerImageView.contentMode = UIViewContentModeScaleToFill;
    [_scrollView addSubview:_centerImageView];
    _rightImageView = [[UIImageView alloc]initWithFrame:CGRectMake(2 * self.frame.size.width, 0, self.frame.size.width, self.frame.size.height)];
    _rightImageView.contentMode = UIViewContentModeScaleToFill;
    [_scrollView addSubview:_rightImageView];
}

#pragma mark 设置默认显示图片
- (void)setDefaultImage {
    //加载默认图片
    // set default center
    [_centerImageView sd_setImageWithURL:_imglist[0] placeholderImage:[UIImage imageNamed:@"img_normal1"]];
    if (_imageCount > 1)
    {
        [_leftImageView sd_setImageWithURL:_imglist[_imageCount - 1] placeholderImage:[UIImage imageNamed:@"img_normal1"]];
        [_rightImageView sd_setImageWithURL:_imglist[1] placeholderImage:[UIImage imageNamed:@"img_normal1"]];
        
    }
    
    _currentImageIndex = 0;
    
    //设置当前页
    _pageControl.currentPage=_currentImageIndex;
    _customPage.currentPage = _currentImageIndex;
    [_customPage setNeedsDisplay];
    
    
    if (_aryInfoData.count != 0) {
        labTitle.text = _aryInfoData[0][@"title"];
        float floatValue = [_aryInfoData[0][@"investment"] floatValue];
        labPrice.text = [NSString stringWithFormat:@"%@", [self comperNumber:@(floatValue)]];
    }

}


#pragma mark 添加分页控件
- (void)addPageControl {
    
    if (_isOkYuanDian) {
        //显示底部
        _pageControl = [[UIPageControl alloc] init] ;
        //注意此方法可以根据页数返回UIPageControl合适的大小
        CGSize size = [_pageControl sizeForNumberOfPages:_imageCount];
        _pageControl.bounds = CGRectMake(0, 0, size.width, size.height);
        _pageControl.center = CGPointMake(self.frame.size.width / 2, self.frame.size.height - 10);
        //设置颜色
        _pageControl.pageIndicatorTintColor = self.color_pageControl ;
        //设置当前页颜色
        _pageControl.currentPageIndicatorTintColor = self.color_currentPageControl ;
        //设置总页数
        _pageControl.numberOfPages = _imageCount;
        [self addSubview:_pageControl];
    }else {
        //显示顶部
        _customPage = [[customPageControl alloc] initWithFrame:(CGRect){8,8,300,30}];
        _customPage.numberOfPages = _imageCount;
        [self addSubview:_customPage];
    }
    
    
}


#pragma mark 添加信息描述控件
- (void)addLabel
{    
    _label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, self.frame.size.width,30)];
    _label.textAlignment = NSTextAlignmentCenter;
    _label.textColor = [UIColor redColor];
    
//    [self addSubview:_label];

}

#pragma mark 滚动停止事件
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    //重新加载图片
    [self reloadImage];
    //移动到中间
    [_scrollView setContentOffset:CGPointMake(_scrollView.frame.size.width, 0) animated:NO];
    //设置分页
    _pageControl.currentPage = _currentImageIndex;
    _customPage.currentPage = _currentImageIndex;
    [_customPage setNeedsDisplay];
    
    if (_aryInfoData.count != 0) {
        labTitle.text = _aryInfoData[_currentImageIndex][@"title"];
        float floatValue = [_aryInfoData[_currentImageIndex][@"investment"] floatValue];
        labPrice.text = [NSString stringWithFormat:@"%@", [self comperNumber:@(floatValue)]];
    }
    
}

#pragma mark 重新加载图片
- (void)reloadImage
{
    [self resumeTimerWithDelay] ;
    
    
    int leftImageIndex,rightImageIndex ;
    CGPoint offset = [_scrollView contentOffset] ;
    
    if (offset.x > self.frame.size.width)
    { //向右滑动
        _currentImageIndex = (_currentImageIndex + 1) % _imageCount ;
    }
    else if(offset.x < self.frame.size.width)
    { //向左滑动
        _currentImageIndex = (_currentImageIndex + _imageCount - 1) % _imageCount ;
    }
    
    [_centerImageView sd_setImageWithURL:_imglist[_currentImageIndex] placeholderImage:[UIImage imageNamed:@"img_normal1"]];
    
//    NSLog(@"manual move at index : %d",_currentImageIndex) ;
    
    //重新设置左右图片
    leftImageIndex  = (_currentImageIndex + _imageCount - 1) % _imageCount ;
    rightImageIndex = (_currentImageIndex + 1) % _imageCount ;

    
    [_leftImageView sd_setImageWithURL:_imglist[leftImageIndex] placeholderImage:[UIImage imageNamed:@"img_normal1"]];
    [_rightImageView sd_setImageWithURL:_imglist[rightImageIndex] placeholderImage:[UIImage imageNamed:@"img_normal1"]];
    
}

- (void)resumeTimerWithDelay
{
    [_timerLoop pause] ;

    if (!bOpenTimer)
    {
        if ([_timerOverflow isValid])
        {
            [_timerOverflow invalidate] ;
        }
        
        _timerOverflow = [NSTimer timerWithTimeInterval:_durationOfScroll
                                                 target:self
                                               selector:@selector(timerIsOverflow)
                                               userInfo:nil
                                                repeats:NO] ;
        
        [[NSRunLoop currentRunLoop] addTimer:_timerOverflow
                                     forMode:NSDefaultRunLoopMode] ;

    }
}

- (void)timerIsOverflow
{
    bOpenTimer = YES ;
    
    if (bOpenTimer)
    {
        [_timerLoop resume] ;
        bOpenTimer = NO ;
        
        [_timerOverflow invalidate] ;
        _timerOverflow = nil ;
    }
}


- (NSString *)comperNumber:(NSString *)number
{
    NSInteger num1 = [number floatValue];
    NSString *strNum = @"";
    if (num1>=10000) {//大于等于1W
        strNum = [NSString stringWithFormat:@"%ld万元",num1/10000];
    }else {
        //小于1万
        strNum = [NSString stringWithFormat:@"%ld元",num1];
    }
    
    
    if (num1 >= 100000000) {
       strNum = [NSString stringWithFormat:@"%ld亿元",num1/100000000];
    }
    
    return strNum;
}




@end
